#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File  : shopClass.py
# @Author: shadow
# @Date  : 2019/11/19
# @Desc  :


class Shop(object):
    def __init__(self, goods_list):
        self.goods_name = [i[0] for i in goods_list]
        self.goods_price = [i[1] for i in goods_list]
        self.goods_count = len(goods_list)
        self.goods_cost = 0
        self.shop_car = {}

    def goods_add(self, num: int):
        price = self.goods_price[num]
        name = self.goods_name[num]
        if name in self.shop_car:
            self.shop_car[name][2] += 1
            self.shop_car[name][3] += price
        else:
            self.shop_car[name] = [num, price, 1, price]  # 购物车显示物品：序号，单价，数量，总价
        self.goods_cost += price

    def goods_remove(self, num: int):
        price = self.goods_price[num]
        name = self.goods_name[num]
        if name in self.shop_car:
            self.shop_car[name][2] -= 1
            self.shop_car[name][3] -= price
            if self.shop_car[name][2] == 0:
                del self.shop_car[name]
            self.goods_cost -= price
        else:
            print("No %s in your shopCar!")

    def goods_find(self, goods):
        '''

        :param goods: if start with "-" means remove
        :return: if no find return False, Otherwise return goods name
        '''
        fn = self.goods_add
        ind = 0
        if goods.startswith("-"):
            goods = goods[1:]
            fn = self.goods_remove

        if goods in self.goods_name:
            ind = self.goods_name.index(goods)
        elif goods.isdigit() and int(goods) < self.goods_count:
            ind = int(goods)
        else:
            print("*********Error name or num of goods!**************")
            return False

        fn(ind)
        return goods

    def shop_car_show(self, cost=False):
        '''

        :param cost: default "False" means show shop_car information,if "True" mean pay
        :return:
        '''
        if cost:
            li = ",".join(["[{}]x{} 共{}".format(i, self.shop_car[i][2], self.shop_car[i][3]) for i in self.shop_car])
            print("购物清单如下：{}, 合计：{}".format(li, self.goods_cost))
        else:
            print("购物车如下：{}, 合计：{}".format(self.shop_car, self.goods_cost))


if __name__ == '__main__':
    products = [['iphone', 6888], ['MacPro', 14800], ['小米6', 2499], ['Coffee', 31], ['Book', 60], ['Nike', 699]]
    shop = Shop(products)
    while True:
        print("---------------goods list of my shop--------------")
        for i in products:
            print(products.index(i), i[0], i[1])
        n = input("Please input the name or num of goods you want:")
        if n != "p":
            if shop.goods_find(n):
                shop.shop_car_show()
        else:
            shop.shop_car_show(True)
            break
# 用到了对象，很厉害，写的很棒，不过有个小问题啊
# 假如我是用户，不知道怎么退出这个程序，是不是应该有个友好的提示呢？
# 咱们作业最好 按照第一周 第二周这样的文件夹格式来，好点。